#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = '__Tony__'
import datetime
import logging

from .common import session_begin
from sqlalchemy.orm import Session, noload
from sqlalchemy import select, and_
from yg_crm import orm, schemas
from typing import List, Dict


def create_template_type(db: Session, template_types: List[schemas.TemplateType]):

    t_arr = [orm.TemplateType(** template_type.model_dump(exclude_unset=True, exclude_none=True, exclude={'create_by', 'create_time'})) if template_type.id else
             orm.TemplateType(** template_type.model_dump(exclude_unset=True, exclude_none=True)) for template_type in template_types]

    for t in t_arr:
        if t.id:
            db.merge(t)
        else:
            db.add(t)

    #   db.refresh(t)
    db.commit()
    return t_arr


def create_template(db: Session, templates: List[schemas.Template]):
    t_arr = [orm.Template(** template.model_dump(exclude_unset=True, exclude_none=True, exclude={'create_by', 'create_time'})) if template.id
             else orm.Template(** template.model_dump(exclude_unset=True, exclude_none=True)) for template in templates]
    # db.add_all(t_arr)
    for t in t_arr:
        if t.id:
            t.del_flag
            t.update_time = datetime.datetime.now()
            db.merge(t)
        else:
            db.add(t)

    db.commit()
    return t_arr


@session_begin
def get_template_types(db: Session):
    res = db.query(orm.TemplateType).all()
    # print(res)
    return res


# session 影响返回为空问题
@session_begin
def get_templates(db: Session):
    res = db.query(orm.Template).all()
    # 属性测试
    # print("Template:", type(res.__dict__['template_type'].__dict__))
    # print("Template_json:", res.to_dict())
    # log.info("class:{0}", class_mapper(orm.Template).columns)
    # log.info("class:{0}", inspect(orm.Template).columns)
    # log.info("class:{0}", [ a for a in orm.Template.__mapper__.attrs])
    # log.info("class:{0}", class_mapper(orm.Template).mapped_table.__dict__)
    return res


@session_begin
def get_templates_by_ids(db: Session, ids: List[int], is_delete: bool = False):
    # select(orm.Template).where(orm.Template.id.in_(ids))
    q = db.query(orm.Template).where(orm.Template.id.in_(ids))
    if is_delete:
        return q.delete()
    else:
        return q.all()


def get_checkBill_by_billNos(db: Session, bill_nos: List[int], is_delete: bool = False):
    # 使用select函数查询数据
    # stmt = select(orm.CheckingBill).where(orm.CheckingBill.bill_no.in_(ids))
    # results = db.execute(stmt).scalars().all()
    conditions = []
    conditions.append(orm.CheckingBill.bill_no.in_(bill_nos))
    conditions.append(orm.CheckingBill.bill_type == 1)
    q = db.query(orm.CheckingBill).where(and_(*conditions))
    if is_delete:
        return q.delete()
    else:
        return q.all()

def delete_checkBillByIds(db: Session, ids: List[int], status: int):
    try:
        # 1. 先删除关联的子表记录
        db.query(orm.CheckingBillFee).filter(orm.CheckingBillFee.id_CheckingBill.in_(ids)).delete(
            synchronize_session=False)
        # 2. 再删除主表记录
        db.query(orm.CheckingBill).filter(orm.CheckingBill.id.in_(ids)).delete(synchronize_session=False)
        db.commit()
        return True
    except Exception as e:
        # 发生异常时回滚会话
        db.rollback()
        print(e)
        return False

def updateCheckBillStatusByIds(db: Session, ids: List[int], status: int):
    try:
        db.query(orm.CheckingBill).filter(orm.CheckingBill.id.in_(ids)).update(
            {orm.CheckingBill.status: status},
            synchronize_session=False
        )
        db.commit()
        return True
    except Exception as e:
        # 发生异常时回滚会话
        db.rollback()
        print(e)
        return False

def create_checkBill(db: Session, data: Dict):
    try:
        valid_fields = [col.name for col in orm.CheckingBill.__table__.columns]
        # 过滤掉无效的键
        valid_data = {key: value for key, value in data.items() if key in valid_fields}
        checkingBill = None
        """
            merged_checkBill = db.merge(checkBill) # 重新返回下orm对象，解决不能persist,db.refresh报错提前跳出
            id 不是主键, 但不能用merge方法
        """

        if 'id' in valid_data:
            checkingBill = db.get(orm.CheckingBill, valid_data['id'])
        if checkingBill:
           for d in valid_data:
                if d != 'id':
                    setattr(checkingBill, d, valid_data[d])
        else:
            checkingBill = orm.CheckingBill(**valid_data)
            checkingBill.create_by = checkingBill.update_by
            checkingBill.create_time = datetime.datetime.now()
            checkingBill.update_time = checkingBill.create_time
            db.add(checkingBill)
        db.commit()
        if not valid_data.get('id'):
            db.refresh(checkingBill)

        # 费用明细部分
        if data.get('feeData'):
            feeDataById = {f['id']: f for f in data.get('feeData').values()}
            checkingBillFeesById = {fee.id_FeeType: fee for fee in checkingBill.checkingBillFees}
            for k,v in feeDataById.items():
                if k in checkingBillFeesById:
                    logging.info("ID:{}已存在,更新金额!",k)
                    checkingBillFeesById[k].amount = feeDataById.get(k).get('amount')
                else:
                    if float(feeDataById.get(k).get('amount')):
                        checkingBill.checkingBillFees.append(
                            orm.CheckingBillFee(
                                id_CheckingBill = checkingBill.id,
                                id_FeeType = k,
                                amount = v.get('amount')
                            )
                        )
            db.commit()
        return checkingBill.id
    except Exception as e:
        # 发生异常时回滚会话
        db.rollback()
        print(e)
        raise e
    finally:
        # 关闭会话
        db.close()

def create_checkedBill(db: Session, data: dict):
    try:
        # 新增BillCheckedRecord数据
        checkedBill = orm.BillCheckedRecord(**data)
        ids = [str(id) for id in data.get('id_checked_bills')]
        checkedBill.id_checked_bills = ",".join(ids)
        checkedBill.create_by = checkedBill.update_by
        checkedBill.update_time = datetime.datetime.now()
        checkedBill.create_time = checkedBill.update_time
        checkedBill = db.merge(checkedBill)
        db.commit()
        db.refresh(checkedBill)
        # 更新checkingBill数据关联
        db.query(orm.CheckingBill).filter(orm.CheckingBill.id.in_(data.get('id_checked_bills'))).update(
    {
            orm.CheckingBill.status: 1,
            orm.CheckingBill.id_accounted: checkedBill.id
           },
           synchronize_session=False
        )
        db.commit()
        return checkedBill.id
    except Exception as e:
        # 发生异常时回滚会话
        db.rollback()
        print(e)
        return 0

def create_invoicedBill(db: Session, data: dict):
    try:
        # 新增BillCheckedRecord数据
        invoicedBill = orm.Invoiced(**data)
        ids = [ str(id) for id in data.get('id_invoiced_bills') ]
        invoicedBill.id_invoiced_bills = ",".join(ids)
        invoicedBill.create_by = invoicedBill.update_by
        invoicedBill.update_time = datetime.datetime.now()
        invoicedBill.create_time = invoicedBill.update_time
        invoicedBill = db.merge(invoicedBill)
        db.commit()
        db.refresh(invoicedBill)
        # 更新checkingBill数据关联
        db.query(orm.CheckingBill).filter(orm.CheckingBill.id.in_(data.get('id_invoiced_bills'))).update(
     {
               orm.CheckingBill.status: 2,
               orm.CheckingBill.id_invoiced: invoicedBill.id
            },
            synchronize_session=False
        )
        db.commit()
        return invoicedBill.id
    except Exception as e:
        # 发生异常时回滚会话
        db.rollback()
        print(e)
        return 0
